package com.cheung.leetcode.backtrack;

import org.junit.jupiter.api.Test;

import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.backtrack
 * @Author :  cheungming
 * @CreateTime : 2024-05-25 09:42:55
 * @Description : 复原IP地址
 * @Version : 1.0
 */
public class Code93Test {

    public List<String> restoreIpAddresses(String s) {
        List<String> res = new java.util.ArrayList<>();
        backtrack(s, 0, new java.util.ArrayList<>(), res);
        return res;
    }

    public void backtrack(String s, int start, List<String> path, List<String> res) {
        if (path.size() == 4 && start == s.length()) {
            res.add(String.join(".", path));
            return;
        }

        for (int i = start; i < s.length(); i++) {
            if (isValid(s.substring(start, i + 1))) {
                path.add(s.substring(start, i + 1));
                backtrack(s, i + 1, path, res);
                path.remove(path.size() - 1);
            }
        }
    }

    private boolean isValid(String s) {
        if ("0".equals(s)) {
            return true;
        }
        if (s.length() > 3 || Integer.parseInt(s) > 255) {
            return false;
        }
        return !s.startsWith("0");
    }

    @Test
    public void test1() {
        String s = "25525511135";
        assert restoreIpAddresses(s).equals(List.of("255.255.11.135", "255.255.111.35"));
    }

    @Test
    public void test2() {
        String s = "0000";
        assert restoreIpAddresses(s).equals(List.of("0.0.0.0"));
    }

    @Test
    public void test3() {
        String s = "101023";
        assert restoreIpAddresses(s).equals(List.of("1.0.10.23", "1.0.102.3", "10.1.0.23", "10.10.2.3", "101.0.2.3"));
    }
}
